package com.lh.controller;

import com.lh.entity.Address;
import com.lh.service.AddressService;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: LuoHang
 * @Date: 2021/2/13 17:05
 * @Description
 */
@Controller
public class AddressController {
    @Autowired
    private AddressService addressService;

    /**
     * 用户中心之个人地址
     *
     * @param userId 对应的用户id
     * @return 视图模型
     */
    @RequestMapping("/getAddressHtml")
    public ModelAndView getAddressHtml(@RequestParam Integer userId) {
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> map = new HashMap<>(4);
        //根据用户的id查询指定用户的所有地址信息
        map.put("userId", userId);
        List<Address> addressList = addressService.getAddress(map);
        for (Address address : addressList) {
            if (address.getAddressStatus() == 1) {
                //当前使用的地址
                modelAndView.addObject("curUseAddress", address);
                break;
            }
        }
        modelAndView.addObject("addressList", addressList);
        modelAndView.setViewName("address");
        return modelAndView;
    }

    /**
     * 地址添加页面
     *
     * @return 视图模型
     */
    @RequestMapping("/addAddressHtml")
    public ModelAndView addAddressHtml() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("address_add");
        return modelAndView;
    }

    /**
     * 添加地址
     *
     * @return 是否添加成功
     */
    @RequestMapping("/addAddress")
    @ResponseBody
    public Map<String, Object> addAddress(@RequestParam String consignee, @RequestParam String consigneePhone, @RequestParam String shipAddress,
                                          @RequestParam String postCode, @RequestParam Integer userId) {
        Address address = new Address(null, consignee, consigneePhone, shipAddress, postCode, userId, 0, null);
        int count = addressService.addAddress(address);
        Map<String, Object> map = new HashMap<>(1);
        map.put("data", count > 0 ? "添加成功" : "添加失败");
        return map;
    }

    /**
     * 地址修改页面
     *
     * @param id 需要被修改的地址的地址id
     * @return 视图模型
     */
    @RequestMapping("/addressEditHtml")
    public ModelAndView addressEdit(@RequestParam Integer id) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("addressInfo", getAddressById(id));
        modelAndView.setViewName("address_edit");
        return modelAndView;
    }

    /**
     * 更新地址信息
     * 默认地址选择
     *
     * @param request 请求对象
     * @param id 更新地址对应的id
     * @return 更新成功与否
     */
    @RequestMapping("/updateAddress")
    @ResponseBody
    public Map<String, Object> updateAddress(HttpServletRequest request, @RequestParam Integer id) {
        String userId = request.getParameter("userId");
        String consignee = request.getParameter("consignee");
        String consignPhone = request.getParameter("consignPhone");
        String shipAddress = request.getParameter("shipAddress");
        String postCode = request.getParameter("postCode");
        String addressStatus = request.getParameter("addressStatus");
        Address address = getAddressById(id);
        Map<String, Object> updateInfo = new HashMap<>(7);

        //更新内容
        updateInfo.put("gmtModified", new Timestamp(System.currentTimeMillis()));
        updateInfo.put("id", id);
        if (!StringUtils.isNullOrEmpty(consignee) && !consignee.equals(address.getConsignee())) {
            updateInfo.put("consignee", consignee);
        }
        if (!StringUtils.isNullOrEmpty(consignPhone) && !consignPhone.equals(address.getConsigneePhone())) {
            updateInfo.put("consigneePhone", consignPhone);
        }
        if (!StringUtils.isNullOrEmpty(shipAddress) && !shipAddress.equals(address.getShipAddress())) {
            updateInfo.put("shipAddress", shipAddress);
        }
        if (!StringUtils.isNullOrEmpty(postCode) && !postCode.equals(address.getPostCode())) {
            updateInfo.put("postCode", postCode);
        }
        if (!StringUtils.isNullOrEmpty(addressStatus) && Integer.parseInt(addressStatus) != address.getAddressStatus()) {
            if (!StringUtils.isNullOrEmpty(userId) && Integer.valueOf(userId).equals(address.getUserId())) {
                //因为每个用户的默认地址只能有一个，如果有切换了默认地址，必须先将之前的默认地址的status设置成0，再更新新默认地址
                if (changeAddress(Integer.valueOf(userId)) > 0) {
                    updateInfo.put("addressStatus", addressStatus);
                }
            }
        }

        //更新数据
        int count = addressService.updateAddress(updateInfo);
        //写入结果
        Map<String, Object> map = new HashMap<>(1);
        map.put("data", count > 0 ? "修改成功" : "修改成功");
        return map;
    }

    /**
     * 方法：getAddressById()
     *
     * @param id 地址对应的id
     * @return 地址对象
     */
    private Address getAddressById(Integer id) {
        return addressService.getAddressById(id);
    }

    /**
     * 更换默认地址
     *
     * @param userId 当前用户id
     * @return int count 是否成功
     */
    private int changeAddress(Integer userId) {
        Map<String, Object> map = new HashMap<>(1);
        map.put("userId", userId);
        List<Address> addressList = addressService.getAddress(map);
        Integer id = null;
        for (Address address : addressList) {
            if (address.getAddressStatus() == 1) {
                id = address.getId();
                break;
            }
        }
        Map<String, Object> updateInfo = new HashMap<>(2);
        updateInfo.put("id", id);
        updateInfo.put("addressStatus", 0);
        return addressService.updateAddress(updateInfo);
    }
}
